package com.zc.common.validator;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * <p>Description : </p>
 *
 * @author : xuhongcao
 * @version : v1.0.0
 * @since : 31/3/2022
 **/
@Component
@Aspect
public class ValidatorAspect {

    /**
     * 定义的Validator的切入点
     */
    @Pointcut("@annotation(com.zc.common.validator.Validator)")
    private void validPointcut() {

    }

    @Around("validPointcut()")
    public Object validateAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Validator validator = this.getValidator(joinPoint);
        Object[] args = joinPoint.getArgs();
        if (validator != null && (args != null && args.length > 0)) {
            checkReqParameters(args, validator);
        }

        return joinPoint.proceed();
    }

    private void checkReqParameters(Object[] args, Validator validator) {
        Class<?>[] clazzs = validator.clazzs();
        if (clazzs == null) {
            return;
        }
        for (Object param : args) {
            for (Class<?> clazz : clazzs) {
                    if(true){
                        ValidationHelper.valid(param);
                    }
            }
        }
    }


    /**
     * 获取注解
     *
     * @param joinPoint
     * @return
     */
    private Validator getValidator(ProceedingJoinPoint joinPoint) throws Exception {
        //获取类的字节码对象，通过字节码对象获取方法信息
        Class<?> targetCls = joinPoint.getTarget().getClass();
        //获取方法签名(通过此签名获取目标方法信息)
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        String methodName = joinPoint.getSignature().getName();
        //获取目标方法上的注解指定的操作名称
        Method targetMethod = targetCls.getDeclaredMethod(methodName, ms.getParameterTypes());
        Validator validator = targetMethod.getAnnotation(Validator.class);

        return validator;
    }


}
